/**
 * 主题管理组合式函数
 * 处理主题切换、持久化存储和动态样式应用
 */

import { ref, computed, watch, onMounted, onUnmounted, readonly } from 'vue'
import { useStorage } from '@vueuse/core'
import {
  themes,
  defaultTheme,
  getTheme,
  getThemeList,
  getResponsiveBackground,
  isResponsiveBackground,
  getAllBackgroundUrls,
  type ThemeConfig,
} from '@/config/themes'

// 全局主题状态
const currentThemeId = useStorage('blog-theme', defaultTheme)
const isTransitioning = ref(false)

export function useTheme() {
  // 当前主题配置
  const currentTheme = computed(() => getTheme(currentThemeId.value))

  // 所有可用主题
  const availableThemes = computed(() => getThemeList())

  // 切换主题
  const setTheme = async (themeId: string) => {
    if (themeId === currentThemeId.value || isTransitioning.value) return

    isTransitioning.value = true

    try {
      // 获取当前屏幕宽度
      const currentWidth = window.innerWidth

      // 使用 View Transition API 进行主题切换
      if ('startViewTransition' in document) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        await (document as any).startViewTransition(() => {
          // 更新 DaisyUI 主题
          document.documentElement.setAttribute('data-theme', themeId)

          // 更新自定义 CSS 变量（传递当前屏幕宽度）
          updateCSSVariables(getTheme(themeId), currentWidth)

          // 更新状态
          currentThemeId.value = themeId
        })
      } else {
        // 降级方案：使用传统 CSS 过渡
        ;(document as Document).documentElement.style.transition = 'all 0.3s ease-in-out'

        // 更新 DaisyUI 主题
        ;(document as Document).documentElement.setAttribute('data-theme', themeId)

        // 更新自定义 CSS 变量（传递当前屏幕宽度）
        updateCSSVariables(getTheme(themeId), currentWidth)

        // 更新状态
        currentThemeId.value = themeId

        // 等待过渡完成
        await new Promise((resolve) => setTimeout(resolve, 300))

        // 移除过渡效果
        ;(document as Document).documentElement.style.transition = ''
      }
    } catch (error) {
      console.error('主题切换失败:', error)
    } finally {
      isTransitioning.value = false
    }
  }

  // 更新 CSS 变量
  const updateCSSVariables = (theme: ThemeConfig, screenWidth?: number, silent = false) => {
    const root = document.documentElement
    const width = screenWidth ?? window.innerWidth

    // 只在首次初始化时打印设备信息
    if (!silent && import.meta.env.DEV) {
      const deviceType = width < 768 ? '📱 移动端' : width < 1024 ? '📱 平板端' : '💻 桌面端'
      console.log(`🎨 主题初始化: ${theme.id} | ${deviceType} (${width}px)`)
    }

    // 更新颜色变量
    Object.entries(theme.colors).forEach(([key, value]) => {
      root.style.setProperty(`--color-${key}`, value)
    })

    // 更新渐变变量
    Object.entries(theme.gradients).forEach(([key, value]) => {
      root.style.setProperty(`--gradient-${key}`, value)
    })

    // 更新阴影变量
    Object.entries(theme.shadows).forEach(([key, value]) => {
      root.style.setProperty(`--shadow-${key}`, value)
    })

    // 更新背景变量（支持响应式图片）
    Object.entries(theme.backgrounds).forEach(([key, value]) => {
      const background = getResponsiveBackground(value, width)

      // 如果是图片URL，设置为 background-image
      if (background.startsWith('http')) {
        root.style.setProperty(`--bg-${key}`, `url(${background})`)
        root.style.setProperty(`--bg-${key}-url`, background)
      } else {
        // 如果是 CSS 类或渐变，直接设置
        root.style.setProperty(`--bg-${key}`, background)
        root.style.setProperty(`--bg-${key}-url`, '')
      }
    })

    // 更新背景类名
    root.className = root.className.replace(/theme-\w+/g, '')
    root.classList.add(`theme-${theme.id}`)
  }

  // 获取主题样式
  const getThemeStyles = (themeId?: string) => {
    const theme = themeId ? getTheme(themeId) : currentTheme.value
    return {
      '--color-primary': theme.colors.primary,
      '--color-secondary': theme.colors.secondary,
      '--color-accent': theme.colors.accent,
      '--gradient-primary': theme.gradients.primary,
      '--gradient-secondary': theme.gradients.secondary,
    }
  }

  // 获取主题类名
  const getThemeClasses = (themeId?: string) => {
    const theme = themeId ? getTheme(themeId) : currentTheme.value
    return {
      [`theme-${theme.id}`]: true,
      'theme-transitioning': isTransitioning.value,
    }
  }

  // 检查是否为暗色主题
  const isDarkTheme = computed(() => {
    return ['dark'].includes(currentTheme.value.id)
  })

  // 获取对比主题（亮色/暗色切换）
  const getContrastTheme = () => {
    return isDarkTheme.value ? 'light' : 'dark'
  }

  // 切换亮色/暗色主题
  const toggleDarkMode = () => {
    setTheme(getContrastTheme())
  }

  // 初始化主题
  const initTheme = () => {
    // 设置初始主题（传递当前屏幕宽度，首次调用打印设备信息）
    document.documentElement.setAttribute('data-theme', currentThemeId.value)
    updateCSSVariables(currentTheme.value, window.innerWidth, false)

    // 监听窗口大小变化，静默更新响应式背景
    const handleResize = () => {
      updateCSSVariables(currentTheme.value, window.innerWidth, true)
    }

    // 防抖处理
    let resizeTimeout: ReturnType<typeof setTimeout>
    const debouncedResize = () => {
      clearTimeout(resizeTimeout)
      resizeTimeout = setTimeout(handleResize, 150)
    }

    window.addEventListener('resize', debouncedResize)

    // 监听系统主题变化
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      const handleSystemThemeChange = (e: MediaQueryListEvent) => {
        if (currentThemeId.value === 'auto') {
          setTheme(e.matches ? 'dark' : 'light')
        }
      }

      mediaQuery.addEventListener('change', handleSystemThemeChange)

      // 返回清理函数
      return () => {
        window.removeEventListener('resize', debouncedResize)
        mediaQuery.removeEventListener('change', handleSystemThemeChange)
        clearTimeout(resizeTimeout)
      }
    }

    return () => {
      window.removeEventListener('resize', debouncedResize)
      clearTimeout(resizeTimeout)
    }
  }

  // 预加载主题资源
  const preloadThemeAssets = async (themeId: string) => {
    const theme = getTheme(themeId)

    // 获取所有背景图片 URL
    const backgroundUrls = getAllBackgroundUrls(theme)

    // 预加载所有图片
    const imagePromises = backgroundUrls.map((url) => {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = resolve
        img.onerror = reject
        img.src = url
      })
    })

    try {
      await Promise.all(imagePromises)
      console.log(`主题 "${theme.name}" 的资源预加载完成`)
    } catch (error) {
      console.warn(`主题 "${theme.name}" 资源预加载失败:`, error)
    }
  }

  // 获取主题预览数据
  const getThemePreview = (themeId: string) => {
    const theme = getTheme(themeId)
    return {
      id: theme.id,
      name: theme.name,
      description: theme.description,
      icon: theme.icon,
      preview: theme.preview,
      colors: {
        primary: theme.colors.primary,
        secondary: theme.colors.secondary,
        base: theme.colors.base,
      },
    }
  }

  return {
    // 状态
    currentThemeId: readonly(currentThemeId),
    currentTheme,
    availableThemes,
    isTransitioning: readonly(isTransitioning),
    isDarkTheme,

    // 方法
    setTheme,
    toggleDarkMode,
    initTheme,
    getThemeStyles,
    getThemeClasses,
    getContrastTheme,
    preloadThemeAssets,
    getThemePreview,
  }
}

// 全局主题实例
export const globalTheme = useTheme()
